package com.example.universitylibraryback.config;

import org.kie.api.KieServices;
import org.kie.api.KieBase;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.Message;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.Arrays;

@Configuration
public class DroolsConfig {
    private static final Logger logger = LoggerFactory.getLogger(DroolsConfig.class);
    private static final String RULES_PATH = "rules/";

    @Bean
    public KieServices kieServices() {
        logger.info("注册KieServices Bean");
        return KieServices.Factory.get();
    }
    
    @Bean
    public KieContainer kieContainer(KieServices kieServices) throws IOException {
        try {
            logger.info("使用Spring注入的KieServices实例");
            
            KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
            logger.info("KieFileSystem创建成功");
            
            // 使用Spring的资源加载机制来确保能正确找到规则文件
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:" + RULES_PATH + "*.drl");
            
            logger.info("找到的规则文件数量: {}", resources.length);
            
            if (resources.length == 0) {
                throw new RuntimeException("未找到任何规则文件，请检查rules目录");
            }
            
            Arrays.stream(resources).forEach(resource -> {
                try {
                    String resourcePath = RULES_PATH + resource.getFilename();
                    logger.info("加载规则文件: {}", resourcePath);
                    
                    // 检查文件是否存在并可读
                    if (resource.exists() && resource.isReadable()) {
                        kieFileSystem.write(ResourceFactory.newClassPathResource(resourcePath, "UTF-8"));
                        logger.info("成功加载规则文件: {}", resource.getFilename());
                    } else {
                        logger.warn("规则文件不可读或不存在: {}", resource.getFilename());
                    }
                } catch (Exception e) {
                    logger.error("加载规则文件失败: {}", resource.getFilename(), e);
                }
            });

            logger.info("开始构建KieBuilder...");
            KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
            
            // 配置构建选项以支持eval表达式
            kieBuilder.buildAll();
            logger.info("KieBuilder构建完成");

            // 检查所有消息（包括警告和错误）
            if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
                logger.error("Drools构建错误:");
                kieBuilder.getResults().getMessages(Message.Level.ERROR).forEach(message -> {
                    logger.error("错误: {}", message.getText());
                    logger.error("行号: {}", message.getLine());
                    logger.error("级别: {}", message.getLevel());
                });
                throw new RuntimeException("Drools规则构建失败");
            }

            // 检查警告信息
            if (kieBuilder.getResults().hasMessages(Message.Level.WARNING)) {
                logger.warn("Drools构建警告:");
                kieBuilder.getResults().getMessages(Message.Level.WARNING).forEach(message -> {
                    logger.warn("警告: {}", message.getText());
                    logger.warn("行号: {}", message.getLine());
                });
            }

            KieModule kieModule = kieBuilder.getKieModule();
            if (kieModule == null) {
                throw new RuntimeException("未能创建有效的KieModule");
            }
            
            logger.info("开始创建KieContainer...");
            KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
            
            // 验证KieBase配置
            KieBase kieBase = kieContainer.getKieBase();
            if (kieBase == null) {
                throw new RuntimeException("KieBase创建失败");
            }
            
            logger.info("KieBase验证成功，包含{}个包", kieBase.getKiePackages().size());
            
            // 测试创建KieSession
            KieSession testSession = kieContainer.newKieSession();
            if (testSession != null) {
                testSession.dispose();
                logger.info("KieSession测试成功");
            }
            
            logger.info("KieContainer创建成功");
            return kieContainer;
            
        } catch (Exception e) {
            logger.error("创建KieContainer失败", e);
            throw e;
        }
    }
}